<template>
  <div class="exchange_mod" :class="themeClass">
    <v-loading v-if="loading" />
    <v-nav :title="$t('Exchange.currency exchange')" v-if="isDayTime === false" title_color="#fff" :class="themeClass"></v-nav>
    <v-nav :title="$t('Exchange.currency exchange')" v-if="isDayTime === true"></v-nav>
    <div class="exchange_mod_box">
      <div class="exchange_mod_box_exchange-type">
        <van-field class="input" readonly clickable name="picker" :value="exchangeBefore" @click="showPicker1 = true" />
        <van-popup v-model="showPicker1" position="bottom">
          <van-picker show-toolbar :columns="baseCurrency" @confirm="onBeforeConfirm" @cancel="showPicker1 = false" :confirm-button-text="$t('info.info10')" :cancel-button-text="$t('info.info11')" />
        </van-popup>
        <img src="@/assets/img/Swap@2x.png" alt="" />
        <van-field class="input" readonly clickable name="picker" :value="exchangeAfter" @click="showPicker2 = true" />
        <van-popup v-model="showPicker2" position="bottom">
          <van-picker show-toolbar :columns="pricingCurrency" @confirm="onAfterConfirm" @cancel="showPicker2 = false" :confirm-button-text="$t('info.info10')" :cancel-button-text="$t('info.info11')" />
        </van-popup>
      </div>
      <div class="exchange_mod_box_exchange-quantity">
        <p>{{ $t('Exchange.Exchange quantity') }}</p>
        <van-field v-model="exchangeNum" @input="handlePrice(exchangeNum)" center :placeholder="$t('Exchange.Please enter the redemption quantity')">
          <template #label>
            <img src="@/assets/img/Database@2x.png" alt="" />
            <span>{{ exchangeBefore.text }}</span>
          </template>
          <template #button>
            <span @click="exchangeNum = userMoney">{{ $t('Exchange.all') }}</span>
          </template>
        </van-field>
      </div>
      <div class="exchange_mod_box_exchange-info">
        <div class="data">
          <p>{{ $t('Exchange.exchange rate') }}</p>
          <p>{{ rate }}</p>
        </div>
        <div class="data">
          <p>{{ $t('Exchange.handling fee') }} {{ exchangeAfter }}</p>
          <p>{{ feeMoney }}</p>
        </div>
        <div class="data">
          <p>{{ $t('Exchange.get') }} {{ exchangeAfter }}</p>
          <p>{{ exchangeMoney }}</p>
        </div>
        <div class="data">
          <p>{{ $t('Exchange.Handling fee ratio') }} %</p>
          <p>{{ commission }}</p>
        </div>
        <div class="data">
          <p>{{ $t('Exchange.Available') }} {{ exchangeBefore }}</p>
          <p>{{ userMoney }}</p>
        </div>
      </div>
    </div>
    <div class="moomoo-bottom">
      <div class="moomoo-bottom-submit">
        <van-button color="#DAAB51" round block @click="submit">{{ $t('Exchange.Confirm exchange') }}</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import Decimal from 'decimal.js'
export default {
  name: 'Exchange',
  data() {
    return {
      symbol: '', // 交易对
      baseCurrency: [], // 基础货币列表
      pricingCurrency: [], // 计价货币列表
      convertible: [], // 可兑换货币
      detail: [], // 兑换货币详情
      isDayTime: false,
      exchangeBefore: '', // 第1货币
      exchangeAfter: '', // 第2货币
      exchangeNum: '', // 兑换数量
      showPicker1: false, // 弹框
      showPicker2: false, // 弹框
      userMoney: '', // 余额数量
      rate: '0:0', // 汇率%
      commission: 0, //手续百分比
      beforeRate: 0, // 基础货币汇率
      afterRate: 0, // 计价货币汇率
      feeMoney: 0, // 手续费
      loading: false
    }
  },
  watch: {
    '$store.state.nightMode': {
      handler(newVal) {
        this.isDayTime = newVal
      },
      immediate: true
    }
  },
  computed: {
    exchangeMoney() {
      // 汇率
      const exchangeRate = this.handleNumber(this.beforeRate / this.afterRate)
      // 金额
      const amount = this.handleNumber(this.exchangeNum / exchangeRate)
      // 手续费
      const fee = amount * (this.commission / 100)
      this.feeMoney = this.handleNumber(fee)
      const num1 = new Decimal(amount)
      const num2 = new Decimal(this.feeMoney)
      const result = num1.minus(num2)
      return this.handleNumber(result)
    },
    themeClass() {
      return this.isDayTime ? '' : 'darknight'
    },
    bgColor() {
      return this.isDayTime ? 'black' : 'white'
    },
    themeClass1() {
      return this.isDayTime ? '' : 'dark_li_color'
    }
  },
  created() {
    this.getExchangeCurrency()
  },
  methods: {
    // 格式划数字
    handleNumber(number, decimalPlaces = 8) {
      let multiplier = Math.pow(10, decimalPlaces)
      let truncated = Math.floor(number * multiplier) / multiplier
      let formatted = truncated.toString()
      return formatted.replace(/(\.\d*?[1-9])0+$/, '\$1')
    },
    // 获取可划转币种
    async getExchangeCurrency() {
      this.loading = true
      await this.$https.get('/platform/getExchangeCurrency').then(res => {
        if (res != undefined && res.code == 1) {
          this.detail = res.data.detail
          this.convertible = res.data.convertible
          this.baseCurrency = res.data.currency
          this.onBeforeConfirm(this.baseCurrency[0])
        }
      })
      this.loading = false
    },
    onBeforeConfirm(value) {
      if (this.exchangeBefore == value) {
        this.showPicker1 = false
        return
      }
      this.exchangeBefore = value
      this.pricingCurrency = this.convertible[this.exchangeBefore]
      this.exchangeAfter = this.pricingCurrency[0]
      this.symbol = this.exchangeBefore + '/' + this.exchangeAfter
      this.exchangeNum = 0
      this.getExchangeRate()
      this.changeExchangeRate()
      this.showPicker1 = false
    },
    onAfterConfirm(value) {
      if (this.exchangeAfter == value) {
        this.showPicker2 = false
        return
      }
      this.exchangeAfter = value
      this.symbol = this.exchangeBefore + '/' + this.exchangeAfter
      this.changeExchangeRate()
      this.showPicker2 = false
    },
    changeExchangeRate() {
      let before = this.exchangeBefore + '/' + this.exchangeAfter
      let after = this.exchangeAfter + '/' + this.exchangeBefore
      if (this.detail[before] != undefined) {
        let parts = this.detail[before].rate.split(':')
        this.beforeRate = parts[0]
        this.afterRate = parts[1]
        this.rate = this.detail[before].rate
        this.commission = this.detail[before].commission
      }

      if (this.detail[after] != undefined) {
        let parts = this.detail[after].rate.split(':')
        this.beforeRate = parts[1]
        this.afterRate = parts[0]
        this.rate = parts[1] + ':' + parts[0]
        this.commission = this.detail[after].commission
      }
    },
    // 获取币种余额
    getExchangeRate() {
      this.$https.get('/wallet/currencyBalance?type=0&currency=' + this.exchangeBefore).then(res => {
        if (res != undefined && res.code == 1) {
          this.userMoney = res.data
        }
      })
    },
    // 限制保留八位小数
    handlePrice(val) {
      if (val !== '' && val.substr(0, 1) === '.') {
        val = ''
      }
      val = val.replace(/^0*(0\.|[1-9])/, '$1') //解决 粘贴不生效
      val = val.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
      val = val.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      val = val.replace(/^(\-)*(\d+)\.(\d\d\d\d\d\d\d\d).*$/, '$1$2.$3') //只能输入八个小数
      if (val.indexOf('.') < 0 && val !== '') {
        if (val.substr(0, 1) === '0' && val.length === 2) {
          val = val.substr(1, val.length)
        }
      }
      if (+val > +this.userMoney) {
        val = this.userMoney
      }
      this.exchangeNum = val
    },
    async submit() {
      if (!this.exchangeNum || this.exchangeNum <= 0) {
        this.$toast(this.$t('Exchange.Please enter the redemption quantity'))
        return
      }
      // this.loading = true
      let params = {
        symbol: this.symbol,
        amount: this.exchangeNum
      }
      await this.$https.post('/Wallet/currencyExchange', params).then(res => {
        if (res != undefined && res.code == 1) {
          this.exchangeNum = ''
          this.getExchangeRate()
        }
      })
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
@import url('~assets/less/vant-form.less');
@import url('~assets/less/index.less');
@import url('./index.less');
</style>
